package com.ykdl.member.kid.gears;

import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;

import oauth.signpost.http.HttpParameters;
import net.wxxr.dataparse.model.DataParseError;
import net.wxxr.dataparse.model.DataState;
import net.wxxr.http.interfaces.ITag;
import net.wxxr.http.request.HttpBaseRequest;
import android.app.Activity;
import android.content.ContentResolver;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.Parcelable;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnTouchListener;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Gallery.LayoutParams;
import cn.jpush.android.api.JPushInterface;

import com.ykdl.member.kid.R;
import com.ykdl.member.KidApp;
import com.ykdl.member.base.GlobalContext;
import com.ykdl.member.constant.KidConfig;
import com.ykdl.member.kid.beans.LaunchBean;
import com.ykdl.member.kid.beans.Web_socket_worker;
import com.ykdl.member.kid.doctor.CatalogsDoctorListActivity;
import com.ykdl.member.kid.prefs.MyPrefs;
import com.ykdl.member.kid.regandlogin.RegAndLoginActivity;
import com.ykdl.member.kid.regandlogin.PerfectUserInfoActivity;
import com.ykdl.member.kid.regandlogin.StateSelectActivity;
import com.ykdl.member.kid.util.AccessTokenKeeper;
import com.ykdl.member.kid.util.MobileUtils;
import com.ykdl.member.views.DetialGallery;
import com.ykdl.net.manager.TaskManager;
import com.ykdl.net.manager.Wxxr;
/**
 * 
 * 启动页面
 * 是新版本，展示新功能的宣传，告知服务器新版本安装， 
 * 不是展现 育儿的欢迎页面
 *
 * 告知服务器客户端启动。
 * @see
 * @since 1.0
 */
public class WelcomeActivity extends Activity {
	@Override
	protected void onStart() {
		// TODO Auto-generated method stub
		super.onStart();
	}

	public static final String TAG = "Welcome";
	private boolean end;
	private boolean  islogin = true ;
	final int[] navigation_res = { R.drawable.welcomebj_01, R.drawable.welcomebj_02, R.drawable.welcomebj_03
			,R.drawable.welcomebj_04,R.drawable.welcomebj_05};
	private DetialGallery gallery;
	private static AccessTokenKeeper mTokenKeeper;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		mTokenKeeper = new AccessTokenKeeper(this);
		KidApp.getInstance().getAppManager().addActivity(this);
		if (MobileUtils.getStringVersion().equals(MyPrefs.getShowNew(this))) {
			showWelcome();
			Handler handler = new Handler() {
				@Override
				public void handleMessage(Message msg) {
					super.handleMessage(msg);
//					if (mTokenKeeper.getmAccessToken()==null) {
//						goRegActivity();
//					}else {
//						goHomeActivity();
//					}
					islogin();
				}
			};
			handler.sendEmptyMessageDelayed(0, 800);
			
	} else {
		showWelcomePictupre();
	}
		
	}
	public void showWelcome() {
		ImageView v = new ImageView(this);
		v.setLayoutParams(new android.view.ViewGroup.LayoutParams(android.view.ViewGroup.LayoutParams.FILL_PARENT,
				android.view.ViewGroup.LayoutParams.FILL_PARENT));
		v.setBackgroundResource(R.drawable.welcome);
		setContentView(v);
	}
	public void showWelcomePictupre() {
		if (!hasShortcut()) {
			createShortCut();
		}
		setContentView(R.layout.show_new);
		gallery = (DetialGallery) findViewById(R.id.shownew);

		gallery.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				// TODO Auto-generated method stub
				if (arg2 == navigation_res.length-1) {
					goRegActivity();
					MyPrefs.setShowNew(WelcomeActivity.this, MobileUtils.getStringVersion()+"");
				}

			}
		});

		end = false;
		gallery.setOnTouchListener(new OnTouchListener() {
			private float startx;

			@Override
			public boolean onTouch(View v, MotionEvent event) {
				// TODO Auto-generated method stub
				int action = event.getAction();
				if (action == MotionEvent.ACTION_DOWN) {

					startx = event.getX();
					if (gallery.getSelectedItemPosition() == navigation_res.length - 2) {
						end = true;
					} else {
						end = false;
					}
				}

				if (action == MotionEvent.ACTION_MOVE) {

					if (startx - event.getX() > 100 && end) {
					}
				}

				return false;
			}

		});

		ImaAdapter adapter = new ImaAdapter(navigation_res, 0, false, true);
		gallery.setAdapter(adapter);
		gallery.setSelection(0);
	}
	
	private void goHomeActivity() {
		Intent t = new Intent(this, HomeActivity.class);   
		startActivity(t);
		finish();
		
	}
	private void goRegActivity() {
		Intent t ;
			 t = new Intent(this,  RegAndLoginActivity.class);
		startActivity(t);
		finish();

	}
	private void goPerfectUserInfoActivity() {
		Intent t ;
			 t = new Intent(this,  StateSelectActivity.class);
		startActivity(t);
		finish();

	}

	// 创建快捷方式
	public void createShortCut() {
		Intent intentnew = new Intent();
		intentnew.setClass(getApplicationContext(), WelcomeActivity.class);
		intentnew.setAction("android.intent.action.MAIN");
		intentnew.addCategory("android.intent.category.LAUNCHER");

		Intent intent = new Intent("com.android.launcher.action.INSTALL_SHORTCUT");
		intent.putExtra("duplicate", false);
		// ComponentName componentName = new
		// ComponentName(this.getPackageName(),
		// "." + getLocalClassName());
		// intent.putExtra(Intent.EXTRA_SHORTCUT_INTENT, new Intent(
		// Intent.ACTION_MAIN).setComponent(componentName));
		intent.putExtra(Intent.EXTRA_SHORTCUT_NAME, getString(R.string.app_name));
		Parcelable icon = Intent.ShortcutIconResource.fromContext(getApplicationContext(), R.drawable.icon);
		intent.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, icon);
		intent.putExtra(Intent.EXTRA_SHORTCUT_INTENT, intentnew);
		sendBroadcast(intent);
	}

	/**
	 * 根据 title 判断快捷方式是否存在
	 * 
	 * @return
	 */
	private boolean hasShortcut() {
		boolean isInstallShortcut = false;
		final ContentResolver cr = getContentResolver();
		final String AUTHORITY = "com.android.launcher.settings";
		final Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY + "/favorites?notify=true");
		Cursor c = cr.query(CONTENT_URI, new String[] { "title", "iconResource" }, "title=?",
				new String[] { getString(R.string.app_name).trim() }, null);
		if (c != null && c.getCount() > 0) {
			isInstallShortcut = true;
		}
		return isInstallShortcut;
	}


	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
//		JPushInterface.onResume(getApplication());
	}
	
	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
//		JPushInterface.onPause(getApplication());
	}
	
	//判断是否登录
	 public void islogin() {
		String  pageurl = KidConfig.APP_START ;
		 HttpBaseRequest  request = Wxxr.getInstance().getBaseRequest(pageurl);
		 TaskManager.startHttpRequest(request, new LoginTag(), LaunchBean.class);
	}
	 class LoginTag implements ITag {

		@Override
		public void refreshUI(Object t, DataState ds) {
			// TODO Auto-generated method stub
			if (t instanceof LaunchBean) {
				LaunchBean launchBean = (LaunchBean) t;
				if (launchBean.getError() == null) {
					Log.e("WelcomeActivity", "去完善资料：launchBean.getTutorial()="+launchBean.getTutorial());
					islogin = launchBean.isLoggedin();
					if (islogin) {
						if (launchBean.getTutorial() == 0) {
							goPerfectUserInfoActivity();
						} else {
							goHomeActivity();
							getWeb_socket();
						}
					} else {
							goRegActivity();

					}
				} else {
					goRegActivity();
				}
				if (launchBean.getJpush_tags()!=null) {
					Set<String> set = new HashSet<String>(Arrays.asList(launchBean.getJpush_tags()));
					JPushInterface.setAliasAndTags(WelcomeActivity.this.getApplicationContext(), launchBean.getAlias(), set);
				}else {
					JPushInterface.setAliasAndTags(WelcomeActivity.this.getApplicationContext(), launchBean.getAlias(), null);
				}
				
			}
		}

		@Override
		public boolean refreshError(DataParseError parseError) {
			
			// TODO Auto-generated method stub
			goHomeActivity();
			return false;
		}

		@Override
		public void refreshCancel() {
			// TODO Auto-generated method stub
			
			}
		}
	 public void getWeb_socket() {
			String pageurl = KidConfig.GET_WEB_SOCKET;
			HttpParameters bodyParams = new HttpParameters();
			HttpBaseRequest request = Wxxr.getInstance().getBaseRequest(pageurl);
			TaskManager.startHttpRequest(request, new getWeb_socketTag(),
					Web_socket_worker.class);
		}

		class getWeb_socketTag implements ITag {

			@Override
			public void refreshUI(Object t, DataState ds) {
				// TODO Auto-generated method stub
				if (t instanceof Web_socket_worker) {
					Web_socket_worker bean = (Web_socket_worker)t;
					if (null==bean.getError()) {
						MyPrefs.setweb_socket(WelcomeActivity.this, "http://"+bean.getWeb_socket_worker().getHost()+":"+bean.getWeb_socket_worker().getPort());
						Log.e("Alan", "-----setOsToke"+bean.getWeb_socket_worker().getHost()+":"+bean.getWeb_socket_worker().getPort());
					}else {
						Toast.makeText(WelcomeActivity.this, "失败,"+bean.getDesc(), 1).show();
					}
				}
			}

			@Override
			public boolean refreshError(DataParseError parseError) {
				// TODO Auto-generated method stub
				return false;
			}

			@Override
			public void refreshCancel() {
				// TODO Auto-generated method stub

			}

		}
	 public class ImaAdapter extends BaseAdapter {
			private int res[];

			ImaAdapter(int[] pres, int rowindex, boolean ploop, boolean pisnav) {
				res = pres;
			}

			@Override
			public int getCount() {
				return res.length;
			}

			@Override
			public Object getItem(int position) {
				// FIXME getItem
				return null;
			}

			@Override
			public long getItemId(int position) {
				// FIXME getItemId
				return position;
			}

			@Override
			public View getView(int position, View convertView, ViewGroup parent) {

				{
					// LinearLayout
					ImageView a = new ImageView(WelcomeActivity.this);
					LayoutParams params = new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
					a.setLayoutParams(params);
					a.setBackgroundDrawable(getResources().getDrawable(res[position]));
					return a;
				}
			}
		}
		 
	 }

